package com.huwaiwai001.echo.nio.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by hww on 2019/3/18 15:19.
 */
public class EchoNioServerTask implements Runnable {

    private SocketChannel channel;

    public EchoNioServerTask(SocketChannel channel) {
        this.channel = channel;
        System.out.println("服务器端连接成功，可以与服务器端进行数据的交互操作...");
    }

    @Override
    public void run() {
        // 开辟一个大小为50的缓存空间
        ByteBuffer buffer = ByteBuffer.allocate(50);
        boolean flag = true;
        try (SocketChannel clientChannel = this.channel) {
            while (flag) {
                // 清理缓存空间 可以重复使用
                buffer.clear();
                // 将数据 缓冲
                int readCount = clientChannel.read(buffer);
                // 读取数据
                String readMessage = new String(buffer.array(), 0, readCount).trim();
                System.out.println("服务端 接收到数据 :" + readMessage);
                // 生成回应消息
                String writeMessage = "【ECHO】" + readMessage + "\n";
                if ("exit".equalsIgnoreCase(readMessage)) {
                    writeMessage = "【ECHO】Bye Byte ..."; // 结束消息
                    flag = false;
                }
                buffer.clear();
                buffer.put(writeMessage.getBytes());
                buffer.flip();
                clientChannel.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
